/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, { useState, useEffect } from 'react';
import { Linking, Alert } from 'react-native';
import { StatusBar, StyleSheet, useColorScheme, View, Text, TextInput, TouchableOpacity } from 'react-native';
import { PermissionsAndroid, Platform } from 'react-native';
import RNImmediatePhoneCall from 'react-native-immediate-phone-call';
import rabbitMQModule, { rabbitMQEventEmitter, CallTaskMessage } from './RabbitMQModule';

import {
  SafeAreaProvider,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';

function App() {
  const isDarkMode = useColorScheme() === 'dark';

  return (
    <SafeAreaProvider>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      <AppContent />
    </SafeAreaProvider>
  );
}


function AppContent() {
  const safeAreaInsets = useSafeAreaInsets();
  const [phoneNumber, setPhoneNumber] = useState('');
  const [deviceId, setDeviceId] = useState('');
  const [queueName, setQueueName] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [lastMessage, setLastMessage] = useState<CallTaskMessage | null>(null);

  // 初始化RabbitMQ
  useEffect(() => {
    initializeRabbitMQ();
    
    // 监听RabbitMQ消息
    const subscription = rabbitMQEventEmitter.addListener(
      'onMessageReceived',
      (message: CallTaskMessage) => {
        console.log('收到RabbitMQ消息:', message);
        setLastMessage(message);
        // 自动拨打电话
        handleAutoCall(message.phone);
      }
    );

    return () => {
      subscription.remove();
      rabbitMQModule.stopRabbitMQ().catch(console.error);
    };
  }, []);

  // 初始化RabbitMQ服务
  const initializeRabbitMQ = async () => {
    try {
      // 获取设备ID和队列名称
      const deviceIdValue = await rabbitMQModule.getDeviceId();
      const queueNameValue = await rabbitMQModule.getQueueName();
      
      setDeviceId(deviceIdValue);
      setQueueName(queueNameValue);
      
      // 启动RabbitMQ服务
      await rabbitMQModule.startRabbitMQ();
      setIsConnected(true);
      
      console.log('RabbitMQ初始化成功');
      console.log('设备ID:', deviceIdValue);
      console.log('队列名称:', queueNameValue);
      
    } catch (error) {
      console.error('RabbitMQ初始化失败:', error);
      Alert.alert('错误', 'RabbitMQ初始化失败，请检查网络连接');
    }
  };

  // 自动拨打电话
  const handleAutoCall = async (phone: string) => {
    try {
      console.log('自动拨打电话:', phone);
      await makePhoneCall(phone);
    } catch (error) {
      console.error('自动拨打电话失败:', error);
    }
  };





// 通用的拨号函数
const makePhoneCall = async (phone: string) => {
  try {
    if (Platform.OS === 'android') {
      console.log("this is android");
      console.log('拨打号码:', phone);
      
      // 请求电话权限
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CALL_PHONE,
        {
          title: '电话权限请求',
          message: '应用需要访问电话功能来拨打电话',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定',
        }
      );

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('拨打号码:', phone);
        RNImmediatePhoneCall.immediatePhoneCall(phone);
      } else {
        Alert.alert('权限被拒绝', '无法拨打电话，因为没有获得电话权限');
      }
    } else {
      // iOS 直接打开拨号界面
      const url = `telprompt:${phone}`;
      await Linking.openURL(url);
    }
  } catch (error) {
    console.error('拨打电话失败:', error);
    Alert.alert('错误', '拨打电话失败，请重试');
  }
};

// 手动拨号函数
const handleCall = async () => {
  if (phoneNumber.trim()) {
    await makePhoneCall(phoneNumber);
  } else {
    Alert.alert('提示', '请输入电话号码');
  }
};

// 刷新连接状态

const refreshConnectionStatus = async () => {
  try {
    // 停止当前RabbitMQ连接
    await rabbitMQModule.stopRabbitMQ();

    // 重新启动RabbitMQ服务
    await rabbitMQModule.startRabbitMQ();

    // 更新连接状态
    setIsConnected(true);

    console.log('RabbitMQ连接已刷新');
  } catch (error) {
    console.error('刷新RabbitMQ连接失败:', error);
    setIsConnected(false);
    Alert.alert('错误', '刷新RabbitMQ连接失败');
  }
};


  return (
    <View style={[styles.container, { paddingTop: safeAreaInsets.top }]}>
      <Text style={styles.title}>智能拨号应用</Text>
      <Text style={styles.subtitle}>支持RabbitMQ消息自动拨号</Text>

      {/* RabbitMQ状态显示 */}
      <View style={styles.statusContainer}>
        <Text style={styles.statusTitle}>系统状态</Text>
        <Text style={styles.statusText}>设备ID: {deviceId}</Text>
        <Text style={styles.statusText}>队列名称: {queueName}</Text>
        <Text style={[styles.statusText, { color: isConnected ? '#4CAF50' : '#F44336' }]}>
          连接状态: {isConnected ? '已连接' : '未连接'}
        </Text>
        <TouchableOpacity style={styles.callButton} onPress={refreshConnectionStatus}>
                    <Text style={styles.buttonText}>刷新连接状态</Text>
        </TouchableOpacity>
      </View>

      {/* 最后收到的消息 */}
      {lastMessage && (
        <View style={styles.messageContainer}>
          <Text style={styles.messageTitle}>最后收到的消息:</Text>
          <Text style={styles.messageText}>电话: {lastMessage.phone}</Text>
          <Text style={styles.messageText}>时间: {lastMessage.time}</Text>
        </View>
      )}

      {/* 手动拨号区域 */}
      <View style={styles.callContainer}>
        <Text style={styles.sectionTitle}>手动拨号</Text>
        <View style={styles.inputRow}>
          <TextInput
            style={styles.input}
            placeholder="请输入电话号码"
            value={phoneNumber}
            onChangeText={setPhoneNumber}
            keyboardType="phone-pad"
          />
          <TouchableOpacity style={styles.callButton} onPress={handleCall}>
            <Text style={styles.buttonText}>拨打</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginBottom: 30,
    textAlign: 'center',
  },
  statusContainer: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  statusTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
    color: '#333',
  },
  statusText: {
    fontSize: 14,
    color: '#666',
    marginBottom: 5,
  },
  messageContainer: {
    backgroundColor: '#E3F2FD',
    padding: 15,
    borderRadius: 10,
    marginBottom: 20,
    borderLeftWidth: 4,
    borderLeftColor: '#2196F3',
  },
  messageTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#1976D2',
  },
  messageText: {
    fontSize: 14,
    color: '#424242',
    marginBottom: 4,
  },
  callContainer: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15,
    color: '#333',
  },
  inputRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    flex: 1,
    height: 40,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 5,
    paddingHorizontal: 10,
    marginRight: 10,
  },
  callButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  buttonText: {
    color: 'white',
    fontWeight: 'bold',
  },
});


export default App;